﻿using System.Data.Common;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace Songhay.Data.GenericWeb.OutputDefinitions
{
    using Songhay.Data.GenericWeb.Procedures;

    /// <summary>
    /// Output procedures from the DBMS
    /// for <see cref="System.Xml.XPath.IXPathNavigable"/> types.
    /// </summary>
    public static partial class XPathNavigableOutput
    {
        /// <summary>
        /// Gets the segment document tree.
        /// </summary>
        /// <param name="commonConnection">The common connection.</param>
        /// <returns>Returns <see cref="System.Xml.XPath.XPathDocument"/>.</returns>
        public static XPathDocument GetSegmentDocumentTree(DbConnection commonConnection)
        {
            string segments = List.SegmentsInnerXml(commonConnection);
            string segmentDocuments = List.SegmentDocuments(commonConnection);

            XPathDocument d = null;
            using(MemoryStream stream = new MemoryStream())
            {
                using(XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Segments");

                    if(!string.IsNullOrEmpty(segments))
                    {
                        writer.WriteRaw(segments);
                    }

                    if(!string.IsNullOrEmpty(segmentDocuments))
                    {
                        writer.WriteRaw(segmentDocuments);
                    }
                    else
                    {
                        writer.WriteStartElement("SegmentDocuments");
                        writer.WriteFullEndElement();
                    }

                    writer.WriteFullEndElement();
                    writer.WriteEndDocument();

                    writer.Flush();

                    stream.Position = 0;
                    d = new XPathDocument(stream);
                }
            }

            return d;
        }
    }
}
